<template>
  <div style="height: 100vh; display: flex; align-items: center; justify-content: center; background-color: #0f9876">
    <div style="display: flex; background-color: white; width: 50%; border-radius: 5px; overflow: hidden; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15)">
      <div style="flex: 1">
        <img src="../assets/logo2.png" alt="系统logo" style="width: 100%; height: 100%; object-fit: cover">
      </div>
      <div style="flex: 1; display: flex; align-items: center; justify-content: center">
        <el-form :model="user" style="width: 80%" :rules="rules" ref="loginRef">
          <div style="font-size: 20px; font-weight: bold; text-align: center; margin-bottom: 20px">欢迎登录课程管理系统</div>
          <el-form-item prop="studentId">
            <el-input prefix-icon="el-icon-user" size="medium" placeholder="请输入账号" v-model="user.studentId"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input prefix-icon="el-icon-lock" size="medium" show-password placeholder="请输入密码" v-model="user.password" @keyup.enter.native="login"></el-input>
          </el-form-item>
          <el-form-item prop="code">
            <div style="display: flex">
              <el-input placeholder="请输入验证码" prefix-icon="el-icon-circle-check" size="medium" style="flex: 1" v-model="user.code"></el-input>
              <div style="flex: 1; height: 36px">
                <valid-code @update:value="getCode" />
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%" @click="login" :loading="loading">
              {{ loading ? '登录中...' : '登 录' }}
            </el-button>
          </el-form-item>
          <div style="display: flex">
            <div style="flex: 1">还没有账号？请 <span style="color: #0f9876; cursor: pointer" @click="$router.push('/register')">注册</span></div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import ValidCode from "@/conponents/ValidCode";

export default {
  name: "Login",
  components: {
    ValidCode
  },
  data() {
    // 验证码校验
    const validateCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else if (value.toLowerCase() !== this.code) {
        callback(new Error('验证码错误'))
      } else {
        callback()
      }
    }

    return {
      loading: false,
      code: '',  // 验证码组件传递过来的code
      user: {
        studentId: '',
        password: '',
        code: ''    // 添加了code字段，修复v-model绑定问题
      },
      rules: {
        studentId: [
          { required: true, message: '请输入账号', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { validator: validateCode, trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
    getCode(code) {
      this.code = code.toLowerCase();
    },
    login() {
      this.$refs['loginRef'].validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            
            const res = await this.$request.post('/login', this.user);
            
            if (res.code === 200 && res.data) {
              // 保存令牌和用户信息
              const userData = res.data;
              localStorage.setItem("user", JSON.stringify(userData));
              
              // 设置请求头的Authorization
              if (userData.token) {
                this.$request.defaults.headers.common['Authorization'] = `Bearer ${userData.token}`;
              }
              
              await this.$router.push('/main/home');
              this.$message.success('登录成功');
            } else {
              this.$message.error(res.message || '登录失败，请检查账号和密码');
              // 刷新验证码
              this.$refs['loginRef'].resetFields();
            }
          } catch (error) {
            console.error('登录请求失败:', error);
            this.$message.error(error.response?.data?.message || '登录请求失败，请稍后重试');
          } finally {
            this.loading = false;
          }
        }
      });
    }
  }
}
</script>

<style scoped>
/* 可以添加响应式样式，使登录框在小屏幕上更友好 */
@media screen and (max-width: 768px) {
  div[style*="width: 50%"] {
    width: 90% !important;
    flex-direction: column;
  }
}
</style>